package com.shuchang.yygh.cmn.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.shuchang.yygh.cmn.service.DictService;
import com.shuchang.yygh.model.cmn.Dict;
import com.shuchang.yygh.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

@Slf4j
public class DictListener extends AnalysisEventListener<DictEeVo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<Dict> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private DictService dictService;

    public DictListener(DictService dictService) {
        this.dictService = dictService;
    }

    //一行一行读取
    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        //批量插入
        log.info("解析到一条数据:{}", JSON.toJSONString(dictEeVo));
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        //调用方法添加数据库
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo, dict);
        cachedDataList.add(dict);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

        //单条插入
        //调用方法添加数据库
        //Dict dict = new Dict();
        //BeanUtils.copyProperties(dictEeVo, dict);
        //dictMapper.insert(dict);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        dictService.saveBatch(cachedDataList);
        log.info("存储数据库成功！");
    }
}
